package com.hoppinzq.service.chatgpt;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hoppinzq.service.aop.annotation.ApiMapping;
import com.hoppinzq.service.aop.annotation.ApiServiceMapping;
import com.hoppinzq.service.aop.annotation.Timeout;
import com.hoppinzq.service.bean.ApiResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;


@ApiServiceMapping(title = "chatGPT服务", description = "chatGPT服务",roleType = ApiServiceMapping.RoleType.RIGHT)
public class ChatGPTService {

    @Timeout(timeout = 30000)
    @ApiMapping(value = "/v1/chat/completions", title = "chatGPT聊天", description = "chatGPT聊天",returnType=false)
    public ApiResponse chat(String key,String text){
        try {
            if(key==null||"".equals(key))
                key="sk-";
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost("https://chatai.1rmb.tk/api/v1/chat/completions");
            request.addHeader("content-type", "application/json");
            request.addHeader("Authorization", "Bearer "+key);
            JSONObject json=new JSONObject();
            json.put("model","gpt-3.5-turbo");
            JSONArray messages=new JSONArray();
            JSONObject message=new JSONObject();
            message.put("role","user");
            message.put("content",text);
            messages.add(message);
            json.put("messages",messages);
            StringEntity params = new StringEntity(json.toString());
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            if(statusCode==200){
                return ApiResponse.success(content.toString());
            }else{
                return ApiResponse.fail(statusCode,content.toString());
            }
        } catch (Exception e) {
            return ApiResponse.fail(5000,e.getMessage());
        }
    }

    @Timeout(timeout = 30000)
    @ApiMapping(value = "/dashboard/billing/credit_grants", title = "token余额", description = "token余额",returnType=false)
    public ApiResponse quota(String key) {
        try {
            if(key==null||"".equals(key))
                key="sk-";
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet("https://chatai.1rmb.tk/api/dashboard/billing/credit_grants");
            request.addHeader("content-type", "application/json");
            request.addHeader("Authorization", "Bearer "+key);
            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            if(statusCode==200){
                return ApiResponse.success(content.toString());
            }else{
                return ApiResponse.fail(statusCode,content.toString());
            }
        } catch (Exception e) {
            return ApiResponse.fail(5000,e.getMessage());
        }
    }

    public String gptAPI(String apiUrl,String token,String query,Boolean isProxy){
        try {
            HttpClient httpClient = HttpClientBuilder.create().build();
            String url="https://api.openai.com/";
            if(isProxy)
                url="https://chatai.1rmb.tk/api/";
            HttpPost request = new HttpPost(url+apiUrl);
            request.addHeader("content-type", "application/json");
            request.addHeader("Authorization", token);
            StringEntity params = new StringEntity(query);
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            if(statusCode==200){
                return content.toString();
            }else{
                return content.toString();
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
